<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>

</body>

</html>
<script>
    let event = {
        list: {},

        on(key, fn) {
            if (!this.list[key]) {
                this.list[key] = [];
            }
            this.list[key].push(fn);
        },

        emit() {
            let key = [].shift.call(arguments),
                fns = this.list[key];
            if (!fns || fns.length === 0) {
                return false;
            }
            fns.forEach(fn => {
                fn.apply(this, arguments);
            });
        },

        remove(key, fn) {
            let fns = this.list[key];

            if (!fns) {
                return false;
            }

            if (!fn) {
                fns && (fns.length = 0); //就会将key值对应缓存列表中的函数清空
            } else {
                fns.forEach((cb, index) => {
                    if (cb == fn) {
                        fns.splice(index, 1);
                    }
                })
            }
        }
    }

    function cat() {
        console.log('一起喵喵喵');
    }
    function dog() {
        console.log('一起旺旺旺');
    }

    event.on('pet', data => {
        console.log('接收数据');
        console.log(data);
    });
    event.on('pet', cat);
    event.on('pet', dog);
    // 取消dog方法的订阅
    event.remove('pet', dog);
    // 发布
    event.emit('pet', ['二哈', '波斯猫']);
</script>